require 'net/http'

#NOTE: twitter disabled user/pass login -- need to use OAuth
$username = 'SENSITIVE'
$password = 'SENSITIVE'

class TweetGen
  def self.generate
    # create request
    req = Net::HTTP::Post.new('/statuses/update.xml')
    req.set_form_data({'status' => self.get_next})
    req.basic_auth($username, $password)
    # send request
    req
  end
  
  def self.get_next
    # power usage
    yday = Power.find(:first, :conditions=>["created_at > :cutoff AND key = :key", {:cutoff => 1.day.ago, :key => "95-DIO_11"}])
    tday = Power.find(:first, :conditions=>["created_at > :cutoff AND key = :key", {:cutoff => 30.minutes.ago, :key => "95-DIO_11"}])
    usage = (tday.value - yday.value)  / 33333.0

    # cost
    cost = usage * 0.12

    # power production
    yday = Power.find(:first, :conditions=>["created_at > :cutoff AND key = :key", {:cutoff => 1.day.ago, :key => "95-DIO_12"}])
    tday = Power.find(:first, :conditions=>["created_at > :cutoff AND key = :key", {:cutoff => 30.minutes.ago, :key => "95-DIO_12"}])
    p1 = (tday.value - yday.value) / 33333.0

    yday = Power.find(:first, :conditions=>["created_at > :cutoff AND key = :key", {:cutoff => 1.day.ago, :key => "95-DIO_13"}])
    tday = Power.find(:first, :conditions=>["created_at > :cutoff AND key = :key", {:cutoff => 30.minutes.ago, :key => "95-DIO_13"}])
    p2 = (tday.value - yday.value) / 33333.0

    production = p1 + p2

    # water usage
    yday = Water.find(:first, :conditions=>["created_at > :cutoff AND key = :key", {:cutoff => 1.day.ago, :key => "95-DIO_10"}])
    tday = Water.find(:first, :conditions=>["created_at > :cutoff AND key = :key", {:cutoff => 30.minutes.ago, :key => "95-DIO_10"}])
    water_usage = (tday.value - yday.value)

    # weather
    noon_weather = Weather.find(:first, :conditions=> ["created_at > :eleven_thirty AND created_at < :twelve_thirty", {:eleven_thirty => 12.hours.ago - 30.minutes, :twelve_thirty => 12.hours.ago + 30.minutes}])
    # temperature
    temperature = noon_weather.temperature

    # conditions
    conditions = noon_weather.conditions

    # "Today: #{"%0.1f" % production} kWh generated, #{"%0.1f" % usage} kWh used, total cost: $#{"%0.2f" % cost}. Gallons of potable water used: #{"%0.0f" % water_usage}. Weather: #{temperature} degrees, #{conditions}."
    "Today: #{"%0.1f" % production} kWh generated, #{"%0.1f" % usage} kWh used, total cost: $#{"%0.2f" % cost}. Weather: #{temperature} degrees, #{conditions}."
  end
end
